package co.yixiang.modules.shop.service.impl;

import co.yixiang.modules.shop.domain.YxProductBase;
import co.yixiang.modules.shop.repository.YxProductBaseRepository;
import co.yixiang.modules.shop.service.YxProductBaseService;
import co.yixiang.modules.shop.service.dto.YxProductBaseQueryCriteria;
import co.yixiang.modules.shop.service.mapper.YxProductBaseMapper;
import co.yixiang.utils.PageUtil;
import co.yixiang.utils.QueryHelp;
import co.yixiang.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.SUPPORTS, readOnly = true)
public class YxProductBaseServiceImpl implements YxProductBaseService {
    @Autowired
    private YxProductBaseRepository yxProductBaseRepository;

    @Autowired
    private YxProductBaseMapper yxProductBaseMapper;

    /**
     * 查询所有未抓取的记录
     *
     * @param criteria
     * @return
     */
    @Override
    public List<YxProductBase> queryAll(YxProductBaseQueryCriteria criteria) {
        return yxProductBaseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(YxProductBase resources) {
        YxProductBase yxProductBase = yxProductBaseRepository.findById(resources.getId()).orElseGet(YxProductBase::new);
        ValidationUtil.isNull(yxProductBase.getId(), "YxProductBase", "id", resources.getId());
        yxProductBase.copy(resources);
        yxProductBaseRepository.save(yxProductBase);
    }

    /**
     * 查询数据分页
     *
     * @param criteria 条件
     * @param pageable 分页参数
     * @return Map<String,Object>
     */
    @Override
    public Map<String, Object> findAll(YxProductBaseQueryCriteria criteria, Pageable pageable) {
        Page<YxProductBase> page = yxProductBaseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(yxProductBaseMapper::toDto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(YxProductBase yxProductBase) {
        yxProductBaseRepository.save(yxProductBase);
    }
}
